<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('Controller', 'Controller');
App::uses('StringUtil', 'Lib');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
	
    var $helpers = array ('Form', 'Html','Acl','Session','Permission','Time');
	var $components = array ('Auth' => array( 'className'=>'PowerAuth' ), 'Acl', 'Session', 'Cookie');
	
	static $flags=array("ita"=>"famfamfam-flag-it","eng"=>"famfamfam-flag-gb");
	static $countryflags=array("italy"=>"famfamfam-flag-it","United Kingdom"=>"famfamfam-flag-gb");
	// static $languageflags=array("Italiano"=>"famfamfam-flag-it","Inglese"=>"famfamfam-flag-gb"
								// ,"Italian"=>"famfamfam-flag-it","English"=>"famfamfam-flag-gb"
								// ,"Italian"=>"famfamfam-flag-it","English"=>"famfamfam-flag-gb"
								// );
	
	
	//var $layoutPath = "bootstrap"; //per cambiare la cartella dove trovare il layout
	 var $layout = "default"; // commento perche si chiama nello stesso modo di quello assegnato sul controler
	
    function beforeFilter() {
        // This callback is executed before the action

        // disabilitare i warning
        Configure::write('debug',2);
		// pr(session_id());die;
		
        // per cambiare i campi username e password di defualt utilizzati dal componente
        //$this->Auth->fields = array('username' => 'email', 'password' => 'password');

        // per specificare condizioni agli oggetti di autenticazione
        $this->Auth->authenticate = array(
 		'all' => array(
 			// 'userModel' => 'Users.User',
 			'scope' => array("OR" => array(array('User.stato' => USER_ATTIVO),array('User.stato' => USER_NON_ATTIVO)))
	 		)
	 		, 'Form' => array('recursive' => 1)
	 		// ,'Basic'
 		);
                
        //Configure AuthComponent
        $this->Auth->authorize = 'Actions';
        $this->Auth->loginAction = array('controller' => 'Users', 'action' => 'login');
        $this->Auth->logoutRedirect = array('controller' => 'Users', 'action' => 'login');
        $this->Auth->loginRedirect = array('controller' => 'home', 'action' => 'index');
        
        // don't require logging in for login and logout actions
        $this->Auth->allow('lang','display');
        // $this->Auth->allow('*');
        // $this->set("utente",$this->Session->read('Auth.User'));
        
		$this->_setLanguage();

		// carico in sessione i parametri
		if(!$this->Session->read('parametri')){
		    $this->loadModel('Parametro');
		    $parametri = $this->Parametro->find("list", array("fields"=>array("Parametro.codice","Parametro.valore")));
		    if($parametri){
                $this->Session->write('parametri',$parametri);
		    } else {
				throw new Exception(__("Attenzione! Non riesco a caricare la lista dei Parametri. contattare l'amministratore"));
		    }
        }
        
         $this->loadModel('Category');
        
    	$this->Category->hasMany["CategoryLang"]["conditions"]=array("CategoryLang.locale" => Configure::read("Config.language"));
        if(!$this->Session->read("valutalist")){
             //carico la lista delle valute
            $valutaList = $this->Category->find("all", array("recursive" => 1, "conditions"=>array("parent_id"=>$this->Session->read("parametri.".PARAMETRO_VALUTA))));
			$valutaList = Set::combine($valutaList, '{n}.Category.id', '{n}.Category');
            $this->Session->write("valutalist",$valutaList);
        }
        if(!$this->Session->read("pagamentolist")){
             //carico la lista delle valute
            $pagamentolist = $this->Category->find("all", array("recursive" => 1, "conditions"=>array("parent_id"=>$this->Session->read("parametri.".PARAMETRO_PAGAMENTO))));
			$pagamentolist = Set::combine($pagamentolist, '{n}.Category.id', '{n}.Category');
            $this->Session->write("pagamentolist",$pagamentolist);
        }
        if(!$this->Session->read("categorylist")){
             //carico la lista delle categorie
            $categoryList = $this->Category->find("list", array("recursive" => 1, "conditions"=>array("parent_id"=>$this->Session->read("parametri.".PARAMETRO_CATEGORIA))));
			// pr($categoryList);die;
            $this->Session->write("categorylist",$categoryList);                                                    
        }
        if(!$this->Session->read("langlist")){
             //carico la lista delle lingue
             $LanguageList = $this->Category->find("all", array("recursive" => 1, "fields" => array("Category.id", "Category.code", "Category.name"), "conditions"=>array("parent_id"=>$this->Session->read("parametri.".PARAMETRO_LINGUA))));
			 $LanguageList = Set::combine($LanguageList, '{n}.Category.id', '{n}.Category');
             $this->Session->write("langlist",$LanguageList);                                                    
        }
        if(!$this->Session->read("categoryPostList")){
             //carico la lista delle categorie
            $categoryPostList = $this->Category->find("list", array("recursive" => 1, "conditions"=>array("parent_id"=>$this->Session->read("parametri.".PARAMETRO_ARGOMENTO))));
			// pr($categoryList);die;
            $this->Session->write("categoryPostList",$categoryPostList);                                                    
        }
                
        //carico tutti i banner sulla pagina e poi li prendo randomicamente da un array
        //***ATTENZIONE : I NUOVI BANNER NON SARANNO INSERITI FINO ALLA CHIUSURA DELLA SESSIONE ATTIVA***
         if(!$this->Session->read("banners")){
             $this->loadModel("Banner");
             //carico la lista delle lingue
            $banners = $this->Banner->find("all", array("conditions"=>array("visible"=>1,"posizione"=>BANNER_SINISTRA,"lang"=>Configure::read('Config.language')) ));
            $this->Session->write("banners.left",$banners);                                                    
            $banners = $this->Banner->find("all", array("conditions"=>array("visible"=>1,"posizione"=>BANNER_DESTRA,"lang"=>Configure::read('Config.language')) ));
            $this->Session->write("banners.right",$banners);                                                    
            $banners = $this->Banner->find("all", array("conditions"=>array("visible"=>1,"posizione"=>BANNER_BASSO,"lang"=>Configure::read('Config.language')) ));
            $this->Session->write("banners.bottom",$banners);
            $banners = $this->Banner->find("all", array("conditions"=>array("visible"=>1,"posizione"=>BANNER_ALTO,"lang"=>Configure::read('Config.language')) ));
            $this->Session->write("banners.top",$banners);
        }
        
		// carico i feed delle nazioni che hanno il live
		$this->set("feeds_live_score", $this->getLiveScoreFeeds());
		$this->set("feeds_live", $this->getLiveFeeds());
		
		// carico la lista dei paesi per il left_menu
         if(!$this->Session->read("country_historical")){
			$this->loadModel('Tournament');
			$country_historical = $this->Tournament->find("all", array("recursive" => -1, 'fields'=>array('DISTINCT Tournament.country','Tournament.country_slug','Tournament.country_code'), "order" => array("Tournament.country")));
            $this->Session->write("country_historical",$country_historical);
		 }
    }

	private function getOddsFeeds() {
		$feeds = Cache::read("feeds_odds","default");
		if (count($feeds)==0 || empty($feeds)) {
		    $this->loadModel('Feed');
			$feeds = $this->Feed->find("all", array("recursive"=>-1, "conditions" => array("type"=>FEED_TYPE_SOCCER_ODDS,"country_code <>" => null), "fields" => array("description","country","country_code"), "order" => array("country")));
			Cache::write("feeds_odds", $feeds, "default");
		}
		return $feeds;
	}
	
	private function getLiveScoreFeeds() {
		$feeds = Cache::read("feeds_live_score","default");
		if (count($feeds)==0 || empty($feeds)) {
		    $this->loadModel('Feed');
			$feeds = $this->Feed->find("all", array("recursive"=>-1, "conditions" => array("type"=>FEED_TYPE_SOCCERNEW,"country_code <>" => null,"country not like" => "%_shedule%"), "fields" => array("description","country","country_code"), "order" => array("country")));
			Cache::write("feeds_live_score", $feeds, "default");
		}
		return $feeds;
	}

	private function getLiveFeeds() {
		$feeds = Cache::read("feeds_live","short");
		if (count($feeds)==0 || empty($feeds)) {
		    $this->loadModel('Feed');
			$feeds = $this->Feed->find("all", array("recursive"=>-1, "conditions" => array("type"=>FEED_TYPE_COMMENTARIES,"country_code <>" => null), "fields" => array("description","country","country_code"), "order" => array("country")));
			Cache::write("feeds_live", $feeds, "short");
		}
		return $feeds;
	}
    
	private function setLangToUrl($lang, $url) {
		// pr($lang);pr($url);die;
		if (substr($url,-3)=="/it" && $lang=="en")
			return str_replace("/it", "/".$lang, $url);
		if (substr($url,-3)=="/en" && $lang=="it")
			return str_replace("/en", "/".$lang, $url);
		
		if ($lang=="it")
			return str_replace("/en/", "/".$lang."/", $url);
		else
			return str_replace("/it/", "/".$lang."/", $url);
	}
	
	public function lang($lang) {
		// pulisco dalla sessione tutti gli elementi caricati
		$this->Session->delete("langlist");
		$this->Session->delete("valutalist");
		$this->Session->delete("pagamentolist");
		$this->Session->delete("categorylist");
		$this->Session->delete("categoryPostList");
		$this->Session->delete("banners");
		$this->Session->delete("country_historical");
		
		// se l'utente e loggato reimposto la lingua dello user
		if ($this->Session->check("Auth.User.id")) {
		    $this->loadModel('User');
			// $this->User->recursive=-1;
			// $this->User->read(null,$this->Session->read("Auth.User.id"));
			// pr($this->User);die;
			$this->User->set("id",$this->Session->read("Auth.User.id"));
		    $this->User->saveField("lang",$lang);
			// aggiorno l'utente in sessione
			$this->Auth->refreshUserData();
		}
		$this->langToSession($lang);
		// pr($this->request->here);
		// pr($this->referer());die;
		
		$this->redirect($this->setLangToUrl($lang, $this->referer()));
	}

	private function langToSession($lang) {
		$this->Session->write('Config.lang', $lang);
		if ($lang=="it") {
			$this->Session->write('Config.language', 'ita');
			$this->Session->write('Config.locale', "it_IT");
		} else if ($lang=="en") {
			$this->Session->write('Config.language', 'eng');
			$this->Session->write('Config.locale', "en_US");
		}
	}
	
	function _setLanguage() {
		// pr($this->Session->read('Config.language'));
		// pr($this->request->params['language']);die;
		if ( isset($this->request->params['lang']) && $this->Session->check('Config.lang') && $this->request->params['lang']!=$this->Session->read('Config.lang') ) {
			$this->langToSession($this->request->params['lang']);
	    }

		if ( isset($this->request->params['lang']) && !$this->Session->check('Config.lang') ) {
			$this->langToSession($this->request->params['lang']);
	    }

	    if ($this->Session->check('Config.language')) {
			Configure::write('Config.language', $this->Session->read("Config.language"));
			Configure::write('Config.locale', $this->Session->read("Config.locale"));
			Configure::write('Config.lang', $this->Session->read("Config.lang"));
			// setlocale per la traduzione delle date
	    }
		setlocale(LC_TIME, Configure::read("Config.language"), Configure::read("Config.locale"));
	}
	
}
